//
//  CONetwork.swift
//  CocoProject
//
//  Created by Ruthless on 2023/7/24.
//

import Moya
import HandyJSON
import QMUIKit

typealias COSuccessBlock = (String)->Void
typealias COErrorBlock = (Int, String)->Void

extension TargetType {
    var baseURL: URL {
        URL(string: KbaseUrl) ?? URL(fileURLWithPath: "")
    }
}

class CONetwork {
    class COBaseBody: HandyJSON {
        var success: Bool = false
        var message: String = ""
        var data: String = ""
        var total: Int = 0
        required init() {
        }
    }
    
    static func sendRequest<T: TargetType>(provider: MoyaProvider<T>, target: T, successBlock: @escaping COSuccessBlock, failedBlock: @escaping COErrorBlock, totalBlock: ((Int)->Void)? = nil) {
        provider.request(target) { result in
            switch result {
                    case let .success(data):
                        let jsonString = String(data: data.data, encoding: .utf8)
                        guard let dic = jsonString?.dic, let model = COBaseBody.deserialize(from: dic) else {
                            failedBlock(-1, "Data processing failed")
                            break
                        }
                    
                    guard model.success else {
                        if model.message.contains("logged in") {
                            COUserManager.userInfo = nil
                            let vc = COLoginIndexViewController()
                            if let _ = UIViewController.getCurrentVc() as? COLoginIndexViewController {
                                break
                            }
                            UIViewController.getCurrentVc()?.navigationController?.setViewControllers([vc], animated: true)
                        } else if model.message.contains("gold coin") {
                            model.message = "Insufficient balance, please recharge"
                        }
                        failedBlock(-1, model.message)
                        break
                    }
                    if model.data.count > 0 {
//                        successBlock(model.data.encodeAES)
                        successBlock(COAesUtil.aesDecrypt(model.data))
                        totalBlock?(model.total)
                        break
                    }
                    successBlock("")
                    break
                case let .failure(error):
                    failedBlock(error.errorCode, error.localizedDescription)
                    break
            }
        }
    }
}

